<?php

namespace Module\Member\Util;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use ModStart\Core\Dao\ModelUtil;
use ModStart\Core\Util\EncodeUtil;
use ModStart\Core\Util\RandomUtil;
use ModStart\Core\Util\SecureUtil;
use Module\Member\Type\MemberStatus;
use Illuminate\Support\Facades\Session;
use Module\Member\Util\MemberUtil;
use ModStart\Core\Util\EventUtil;
use Module\Member\Events\MemberUserLoginedEvent;
class MemberBlogUtil
{



    /**
     * @param $filter
     * 登录
     */
    public static function login($filter)
    {
        $where = ['username' => $filter['username']];
        $orwhere = ['phone' => $filter['username']];
//        $option['whereOperate'] = ['username', 'like', "%$keywords%"];
        $user = ModelUtil::model("member_user")->where($where)->orWhere($orwhere)->first();
        if ($user) {
            $pass = EncodeUtil::md5WithSalt($filter['password'], $user->passwordSalt);
            if ($pass != $user->password) {
                return '你输入的密码有误,请重新输入!';
            }
            //生成token
            $sect = $filter['username'] . ',' . $pass . ',' . RandomUtil::lowerChar(6) . ',' . time();
            $token = self::makeToken($filter['username'], $sect);
            Cache::put($filter['username'], $token, 120);
            Session::put('memberUserId', $user->id);
            MemberUtil::fireLogin($user->id);
            EventUtil::fire(new MemberUserLoginedEvent($user->id));
//            $token = self::deMakeToken($filter['username'],"Wm1YcFFka3Vxa1dOUENjNUcwRFJUWkNUbmlGalZxM1JnVk5jcHJNVmpEaHlaK1pLZ1RYQU81ck1Yb3k1TzVTdkdiVi9IUDlUenJkZE5oVzdQRzBNNy9YL25BaTZoSVdHaXZycFdPejB2NWM9Ojq6P8Xjlagci6zQuPN0RMFy");
//            ModelUtil::model("member_user")->where(["id" => $user->id])->update(['lastLoginTime' => date("Y-m-d H:i:s", time())]);
            return ['api_token' => $token, 'user_Id' => $user->id];
        }
        return '该账号不存在!';
    }

    /**
     * @param $filter
     * 绑定账户
     */
    public static function bindUserBlog($filter)
    {
        $info = self::getUserInfo($filter['user_id']);
//        if (!$info->pay_pass) {
//            return "请先设置支付密码!";
//        }
        if (!$info) {
            return "该用户不存在,不能绑定!";
        }
//        $pass = EncodeUtil::md5WithSalt($filter['pass'], $info->passwordSalt);
//        if ($pass != $info->pay_pass) {
//            return "支付密码错误,请重新输入!";
//        }
        $blog = ModelUtil::model("blog")->where(['id'=>$filter['blog_id']])->first();
        if(!$blog){
            return "该账户类型不存在,不能绑定!";
        }
        $wallet = ModelUtil::model("bindwallet")->where(['user_id'=>$filter['user_id'],'blog_id'=>$filter['blog_id']])->first();
        if($wallet){
            return "您已绑定该账号,不能重复的绑定!";
        }
        //绑定
        $memberUser = ModelUtil::insert('bindwallet', [
            'user_id' => $filter['user_id'],
            'blog_id' => $filter['blog_id'],
        ]);
        return $memberUser;
    }

    /**
     * @param $filter
     * @return array|string
     * 绑定支付宝
     */
    public static function bindUserAlipay($filter)
    {
        $info = self::getUserInfo($filter['user_id']);
        if (!$info->pay_pass) {
            return "请先设置支付密码!";
        }
        $pass = EncodeUtil::md5WithSalt($filter['pass'], $info->passwordSalt);
        if ($pass != $info->pay_pass) {
            return "支付密码错误,请重新输入!";
        }
        $lit['ali_name'] = $filter['ali_name'];
        $lit['ali_account'] = $filter['ali_account'];
        //绑定
        $memberUser = ModelUtil::update("member_user", ['id' => $filter['user_id']], $lit);
        return $memberUser;
    }

    /**
     * @param $filter
     * @return array|string
     * 设置支付密码
     */
    public static function setPayPass($filter)
    {
        $info = self::getUserInfo($filter['user_id']);
        $pass = EncodeUtil::md5WithSalt($filter['pass'], $info->passwordSalt);
        $lit['pay_pass'] = $pass;
        //绑定
        $memberUser = ModelUtil::update("member_user", ['id' => $filter['user_id']], $lit);
        return $memberUser;
    }

    public static function updateUser($id, $data)
    {
        return ModelUtil::update('member_user', ['id' => $id], $data);
    }












    /**
     * @param $username
     * @param $data
     * @return 生成token
     *
     */
    public static function makeToken($username,$data)
    {
        return md5(md5($data));
    }

    /**
     * @param $username
     * @param $data
     * @return false|string|null
     * 解密token
     */
    public static function deMakeToken($username,$data)
    {
        return SecureUtil::aesDecode($username,$data);
    }



    /**
     * @param $filter
     * 获取用户信息
     */
    public static function getUserInfo($user_id)
    {
        return ModelUtil::model('member_user')->find($user_id);
    }

    /**
     * @param $data
     * @return array
     * 注册
     */
    public static function register($data)
    {
        try {
           DB::beginTransaction();
            $passwordSalt = Str::random(16);
            $memberUser = ModelUtil::insert('member_user', [
                'status' => MemberStatus::NORMAL,
                'username' => $data['username'],
//            'email' => $email,
                'phone' => $data['phone'],
                'nickname' => $data['username'],
                'gender' => $data['gender'],
                'id_card' => $data['id_card'],
                'born' => $data['born'],
                'password' => EncodeUtil::md5WithSalt($data['password'], $passwordSalt),
                'passwordSalt' => $passwordSalt,
                'vipId' => MemberVipUtil::defaultVipId(),
                'groupId' => MemberGroupUtil::defaultGroupId(),
                'isDeleted' => false,
            ]);
            if ($memberUser) {
                //绑定
                $wallet = ModelUtil::model("blog")->whereIn("id", [1, 2])->get();
                $lit = [];
                foreach ($wallet as $k => $v) {
                    $lit[$k]['user_id'] = $memberUser["id"];
                    $lit[$k]['blog_id'] = $v->id;
                    $lit[$k]['rmb_price'] = 0;
                }
                ModelUtil::insertAll('bindwallet', $lit);
            }
            // 提交
            DB::commit();
            return $memberUser;
        } catch (\Exception $e) {
            DB::rollBack();
            // 在这里处理异常
            return false;
        }
    }
    
    /***
     * @param $user_name
     * @param $phone
     * 判断用户是否存在
     */
    public static function getUserExist($user_name, $phone)
    {
        $user_name = ModelUtil::get('member_user', ['username' => $user_name]);
        if ($user_name) {
            return 1;
        }
        $phone = ModelUtil::get('member_user', ['phone' => $phone]);
        if ($phone) {
            return 2;
        }
        return 3;
    }
    
    
    /***
     *获取用户信息 
     */
    public static function getUserDetail($user_id){
        $filed = ["username","phone","ali_name","ali_account","gender","id_card","born","nickname"];
        $info =  $user_name = ModelUtil::get('member_user',['id' => $user_id] ,$filed);
        if($info['ali_name'] && $info['ali_account']){
            $info['is_alibind'] = 1;
        }else{
            $info['is_alibind'] = 0;
        }
        unset($info['ali_name']);
          unset($info['ali_account']);
        return $info;
    }
    
    
    
    


    public static function getUserAddress($memberUserId, $id)
    {
        $record = ModelUtil::get('member_address', ['id' => $id, 'memberUserId' => $memberUserId]);
        ModelUtil::decodeRecordBoolean($record, ['isDefault']);
        return $record;
    }

    public static function listUserAddresses($memberUserId)
    {
        $records = ModelUtil::model('member_address')->where(['memberUserId' => $memberUserId])->orderBy('id', 'desc')->orderBy('isDefault', 'desc')->get()->toArray();
        ModelUtil::decodeRecordsBoolean($records, ['isDefault']);
        return $records;
    }

    public static function delete($id)
    {
        ModelUtil::delete('member_address', ['id' => $id]);
    }

    public static function resetDefault($memberUserId)
    {
        ModelUtil::update('member_address', ['memberUserId' => $memberUserId], ['isDefault' => false]);
    }

    public static function update($id, $data)
    {
        return ModelUtil::update('member_address', ['id' => $id], $data);
    }

    public static function insert($data)
    {
        return ModelUtil::insert('member_address', $data);
    }

    public static function getDefault($memberUserId)
    {
        $address = ModelUtil::get('member_address', ['memberUserId' => $memberUserId, 'isDefault' => true]);
        if (empty($address)) {
            $address = ModelUtil::get('member_address', ['memberUserId' => $memberUserId]);
        }
        return $address;
    }

    public static function clearDefault($memberUserId)
    {
        ModelUtil::update('member_address', ['memberUserId' => $memberUserId], ['isDefault' => false]);
    }

    public static function truncate($memberUserId)
    {
        ModelUtil::delete('member_address', ['memberUserId' => $memberUserId]);
    }

}
